<template>
    <section>
        <!--新增界面-->
        <el-col :sm="24" :lg="18">
            <div class="grid-content bg-purple" :style="{backgroundColor:titleColor}">
                <div class="dev-title">添加告警规则</div>
            </div>
            <div class="col-bg clearfix">
                <el-form :model="addForm" label-width="140px" :rules="addFormRules" ref="addForm">
                    <el-form-item label="告警模板">
                        <el-select v-model="alarm_triggerid" placeholder="请选择告警模板" @change="triggerget()" class="grade">
                            <el-option v-for="item in alarm_triggerlist" :label="item.name"
                                :value="item.alarmTriggerId"></el-option>
                            <!-- <el-option label="类型2" value="2"></el-option> -->
                        </el-select>
                    </el-form-item>
                    <el-form-item label="告警点名称" prop="name" class="grade">
                        <el-input v-model="addForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="告警类型" prop="alarmTypeId" class="grade">
                        <el-select v-model="addForm.alarmTypeId" placeholder="请选择告警类型">
                            <el-option v-for="item in alaem_type" :label="item.name" :value="item.id"></el-option>
                            <!-- <el-option label="类型2" value="2"></el-option> -->
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备类型" class="grade" prop="deviceTypeId">
                        <el-select v-model="addForm.deviceTypeId" placeholder="请选择设备类型">
                            <el-option v-for="item in typelist" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据模板ID" class="grade" prop="deviceDataRecipeId">
                        <el-select v-model="addForm.deviceDataRecipeId" @change="second()" placeholder="请选择数据模板ID">
                            <el-option v-for="item in deviceDataRecipe" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据模板数据点ID" class="grade" prop="deviceDataRecipeBodyId">
                        <el-select v-model="addForm.deviceDataRecipeBodyId" placeholder="请选择数据模板数据点ID">
                            <el-option v-for="item in deviceDataRecipeBody" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="告警等级" class="grade" prop="level">
                        <el-select v-model="addForm.level" placeholder="请选择告警等级">
                            <el-option v-for="item in alaem_grade" :label="item.remark" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="数据点" class="grade">
                <el-input v-model="addForm.register"></el-input>
            </el-form-item> -->
                    <el-form-item label="触发条件" class="grade" prop="triggerCondition">
                        <el-select v-model="addForm.triggerCondition" @change="Condition()">
                            <el-option v-for="item in unitlist" :label="item.remark" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="触发A值" class="grade" prop="inputMin" >
                        <el-input type='number' v-model="addForm.inputMin" :disabled="addFormRules.inputMin.length==0"></el-input>
                    </el-form-item>
                    <el-form-item label="触发B值" class="grade" prop="inputMax">
                        <el-input type='number' v-model="addForm.inputMax" :disabled="addFormRules.inputMax.length==0"></el-input>
                    </el-form-item>
                    <el-form-item label="告警方式" prop="alarmMode">
                        <el-radio-group v-model="addForm.alarmMode">
                            <el-radio label="1">微信</el-radio>
                            <el-radio label="2">短信</el-radio>
                            <!-- <el-radio label="3">邮件</el-radio> -->
                        </el-radio-group>
                    </el-form-item>
                    <!-- <el-form-item label="是否存储数据">
                <el-radio-group v-model="addForm.isSave">
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                </el-radio-group>
            </el-form-item> -->
                    <!-- <el-form-item label="启用状态" prop="status">
                        <el-radio-group v-model="addForm.status">
                            <el-radio label="0" value="0" checked>不启用</el-radio>
                            <el-radio label="1" value="1">启用</el-radio>
                        </el-radio-group>
                    </el-form-item> -->
                    <el-form-item label="告警触发推送内容" prop="customContent">
                        <el-input type="textarea" v-model="addForm.customContent"></el-input>
                    </el-form-item>
                    <el-form-item label="告警解除推送内容" prop="customContentNormal">
                        <el-input type="textarea" v-model="addForm.customContentNormal"></el-input>
                    </el-form-item>
                    <el-form-item label="备注"  >
                        <el-input type="textarea" v-model="addForm.remark"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="告警组">
                        <el-transfer v-model="addForm.alarmUserLists" :button-texts="['到左边', '到右边']" :data="userlists"
                            style="margin-left:30px;padding-bottom:20px;"></el-transfer>
                    </el-form-item> -->
                    <el-form-item label="告警人/组">
                        <el-transfer :titles="['可选', '已选']" :button-texts="['到左边', '到右边']"
                            v-model="addForm.alarmUserList" :data="userlist"
                            style="padding-left:30px;padding-bottom:20px;"></el-transfer>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align: center;">
                    <!-- <el-button @click.native="addFormVisible = false">取消</el-button> -->
                    <el-button :type="buttonColor" @click.native="addSubmit" :loading="addLoading">提交</el-button>
                </div>
            </div>
        </el-col>
        <!-- <el-col :sm="24" :lg="6" style="padding-left: 20px">
            <div class="grid-content bg-purple">
                <div class="dev-title">帮助</div>
            </div>
            <div class="col-bg clearfix">
                <el-collapse v-model="activeName" accordion>
                    <el-collapse-item title="告警规则设置" name="1">
                        <div>告警规则可以设置不同的设备和数据点绑定不同的告警方式。</div>
                        <div>当设备触发告警条件时会进入告警状态，服务器推送告警消息，后面的告警信息将不再推送，直到恢复正常数据时推送设备恢复消息。</div>
                        <div>触发器仅支持非数据透传的通讯协议设备。</div>
                    </el-collapse-item>
                    <el-collapse-item title="触发规则" name="2">
                        <div>默认触发规则为状态切换告警：</div>
                        <div>例：温度大于40告警；温度到50会触发告警推送并存储告警信息，再次上传“60”不会触发告警且不保存数据。温度到30，会触发恢复告警推送并存储告警消息</div>
                    </el-collapse-item>
                    <el-collapse-item title="保存规则" name="3">
                        <div>保存规则指的是告警数据的保存规则：</div>
                        <div>保存：
                            保存触发器触发告警时的数据，以及从告警状态恢复到正常状态时的数据。</div>
                        <div>不保存：
                            不保存告警数据。</div>
                    </el-collapse-item>

                </el-collapse>
            </div>
        </el-col> -->
    </section>
</template>

<script>
    import {
        device_data_recipe_query,
        alarms_query_user,
        alarm_trigger_post,
        alarm_group_query,
        alarm_type_query,
        device_data_recipe_list_body,
        dict_query,
        alarm_trigger_template_query,
        alarm_trigger_template_get,
        device_type_query
    } from '../../../api/api';

    export default {
        data() {

            const generateData = _ => {
                const data = [];
                let para = {};
                //NProgress.start();
                alarms_query_user(para).then((res) => {
                     this.begCode(res.code,res.message);
                    // this.total = res.data.totalCount;
                    if (res.code == 0) {
                        for (let i in res.data.list) {
                            data.push({
                                type: 1,
                                key: parseInt(res.data.list[i].id) + 1000000,
                                label: res.data.list[i].name + "(告警人)"
                            });
                        }
                    } else {
                        this.$router.push({
                            path: '/login'
                        });
                    }
                    //NProgress.done();
                });
                alarm_group_query(para).then((res) => {
                     this.begCode(res.code,res.message);
                    // this.total = res.data.totalCount;
                    if (res.code == 0) {
                        for (let i in res.data.list) {
                            data.push({
                                type: 2,
                                key: res.data.list[i].id,
                                label: res.data.list[i].name + "(告警组)"
                            });
                        }
                    } else {
                        this.$router.push({
                            path: '/login'
                        });
                    }
                    //NProgress.done();
                });
                // setTimeout(() => {
                //     for (let i in data) {
                //         data[i].key = i;
                //     }
                //     console.log(data)
                // }, 500)

                return data;
            };
            return {
                typelist: '',
                alarm_triggerid: '',
                alarm_triggerlist: '',
                activeName: '1',
                alaem_grade: '',
                alaem_type: '', //告警类型
                deviceDataRecipe: '', //数据配方
                deviceDataRecipeBody: '', //数据配方数据点
                alarmUserList: {}, //告警组ID
                alarmUserLists: {}, //告警人ID
                alarmTypeValue: '',
                userlist: generateData(),
                addLoading: false,
                addFormRules: {
                    name: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    },{ min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                    alarmTypeId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    deviceTypeId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    deviceDataRecipeId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    deviceDataRecipeBodyId: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    level: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    register: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    triggerCondition: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    inputMin: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    inputMax: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    alarmMode: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    isSave: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    status: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    customContent: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    customContentNormal: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],
                    remark: [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }],


                },
                //新增界面数据
                addForm: {
                    deviceTypeId: localStorage.getItem('typepost'),
                    alarmTypeId: '',
                    name: '',
                    deviceDataRecipeId: '',
                    deviceDataRecipeBodyId: '',
                    level: '',
                    register: '',
                    triggerCondition: '',
                    inputMin: '',
                    inputMax: '',
                    alarmMode: '1',
                    isSave: '0',
                    status: '0',
                    customContent: '',
                    customContentNormal: '',
                    remark: '',
                    alarmTriggerGroupList: [],
                    alarmUserList: [],
                    alarmUserLists: []
                },
                unitlist: ''

            }
        },
        computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
        methods: {
            Condition() {
                console.log(this.addForm.triggerCondition);
                if (this.addForm.triggerCondition == 0 || this.addForm.triggerCondition == 4) {
                    this.addFormRules.inputMin = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                    this.addFormRules.inputMax=[];
                } else if (this.addForm.triggerCondition == 1) {
                    this.addFormRules.inputMin=[];
                    this.addFormRules.inputMax = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                } else if (this.addForm.triggerCondition == 2 || this.addForm.triggerCondition == 3) {
                    this.addFormRules.inputMax = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                    this.addFormRules.inputMin = [{
                        required: true,
                        message: '必填',
                        trigger: 'blur'
                    }]
                }
            },
            triggerget() {
                let para = {
                    id: this.alarm_triggerid,
                };
                alarm_trigger_template_get(para).then((res) => {
                     this.begCode(res.code,res.message);
                    if (res.code == 0) {
                        //NProgress.done();
                        let num = res.data;
                        this.addForm = {
                            alarmTypeId: num.alarmTypeId,
                            name: '',
                            // deviceDataRecipeId: num.deviceDataRecipeId,
                            // deviceDataRecipeBodyId: num.deviceDataRecipeBodyId.toString(),
                            level: num.level.toString(),
                            register: num.register,
                            triggerCondition: num.triggerCondition,
                            inputMin: num.inputMin,
                            inputMax: num.inputMax,
                            alarmMode: num.alarmMode,
                            isSave: num.isSave,
                            status: num.status,
                            customContent: num.customContent,
                            customContentNormal: num.customContentNormal,
                            remark: num.remark,
                            alarmTriggerGroupList: [],
                            alarmUserList: [],
                            alarmUserLists: []
                        }
                        this.second();
                        this.Condition();
                    }
                });
            },
            second: function () {
                if (this.addForm.deviceDataRecipeId) {
                    let para = {
                        deviceDataRecipeId: this.addForm.deviceDataRecipeId,
                    };
                    device_data_recipe_list_body(para).then((res) => {
                         this.begCode(res.code,res.message);
                        if (res.code == 0) {
                            //NProgress.done();
                            this.deviceDataRecipeBody = res.data.list;
                        }
                    });
                } else {
                    this.deviceDataRecipeBody = {};
                }

            },
            addSubmit: function () {

                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {

                            console.log(this.userlist)
                            console.log(this.addForm.alarmUserList)
                            for (let i in this.userlist) {
                                for (let j in this.addForm.alarmUserList) {
                                    if (this.addForm.alarmUserList[j] == this.userlist[i].key) {
                                        console.log(this.userlist[i])
                                        if (this.userlist[i].type == 1) {
                                            // console.log(this.userlist[i].key-1000000)
                                            this.addForm.alarmTriggerGroupList.push({
                                                "type": 1,
                                                "alarmTypeValue": this.userlist[i].key -
                                                    1000000
                                            });
                                        } else {
                                            this.addForm.alarmTriggerGroupList.push({
                                                "type": 2,
                                                "alarmTypeValue": this.userlist[i].key
                                            });
                                        }

                                        console.log(this.addForm.alarmTriggerGroupList)
                                    }
                                }
                            }

                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);

                            alarm_trigger_post(para).then((res) => {
                                 this.begCode(res.code,res.message);
                                this.addLoading = false;
                                if (res.code == 0) {
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['addForm'].resetFields();
                                    this.addFormVisible = false;
                                    this.$router.push({
                                        path: "/alarms/triggers"
                                    });

                                }

                            });
                        });
                    }
                });
            }


        },
        mounted() {

            let para = {
                pageNo: 1,
                pageSize: 1000
            };
            let para1 = {
                name: 'triggerCondition',
                pageSize: 999,
                pageNo: 1,
            }
            alarm_trigger_template_query(para).then((res) => {
                 this.begCode(res.code,res.message);
                if (res.code == 0) {
                    this.addLoading = false;

                    this.alarm_triggerlist = res.data.list;


                }

            });
            device_type_query(para).then((res) => {
                 this.begCode(res.code,res.message);

                this.addLoading = false;
                if (res.code == 0) {
                    this.typelist = res.data.list;
                } else {
                    this.$message({
                        message: res.message,
                        type: 'warning'
                    });
                }

            });
            dict_query(para1).then((res) => {
                 this.begCode(res.code,res.message);
                if (res.code == 0) {
                    this.addLoading = false;

                    this.unitlist = res.data.list;


                }

            });
            let para2 = {
                name: 'alarmLevel',
                pageSize: 999,
                pageNo: 1,
            }
            dict_query(para2).then((res) => {
                 this.begCode(res.code,res.message);
                if (res.code == 0) {
                    this.addLoading = false;

                    this.alaem_grade = res.data.list;


                }

            });
            alarm_type_query(para).then((res) => {
                 this.begCode(res.code,res.message);
                if (res.code == 0) {
                    //NProgress.done();

                    this.alaem_type = res.data.list;

                }

            });

            device_data_recipe_query(para).then((res) => {
                if (res.code == 0) {
                    //NProgress.done();
                    this.deviceDataRecipe = res.data.list;

                }

            });
            
            if(sessionStorage.getItem('deviceDataRecipeBodyId') && sessionStorage.getItem('deviceDataRecipeId')){
                this.addForm.deviceDataRecipeBodyId = sessionStorage.getItem('deviceDataRecipeBodyId')
                this.addForm.deviceDataRecipeId = sessionStorage.getItem('deviceDataRecipeId')
            }
            let para3 = {
                // deviceDataRecipeBodyId: this.addForm.deviceDataRecipeBodyId,
                deviceDataRecipeId: this.addForm.deviceDataRecipeId
            }
            device_data_recipe_list_body(para3).then((res) => {
                if(res.code == 0){
                    this.deviceDataRecipeBody = res.data.list
                }
            })

        }
    }
</script>

<style scoped>

</style>